package top.ljjapp.security.browser;
/**
 * @FileName: BrowserSecurityController.java
 * @Package: top.ljjapp.security.browser
 * @Author: lijiajun
 * <br/>
 * @Created: 2018/11/22 11:52
 */

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import top.ljjapp.security.browser.support.SimpleResponse;
import top.ljjapp.security.core.properties.SecurityProperties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p></p>
 * <p/>
 * <PRE>
 * <BR> 修改记录
 * <BR>-----------------------------------------------
 * <BR> 修改日期 修改人 修改内容
 * </PRE>
 *
 * @author lijiajun
 */
@RestController
@Slf4j
public class BrowserSecurityController {

    //从缓存中拿到引发跳转的请求 接到请求时会将请求放到seesion缓存中
    private RequestCache requestCache = new HttpSessionRequestCache();

    //spring的一个工具,作跳转使用
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    //导入封装的security配置
    @Autowired
    private SecurityProperties securityProperties;

    /**
     * 身份认证之前跳转到这里
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED) //401未授权
    public SimpleResponse requireAuthtication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SavedRequest savedRequest = requestCache.getRequest(request, response);

        //判断缓存中是否有请求
        if (savedRequest != null) {
            String redirectUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是" + redirectUrl);
            //如果是html请求，跳转到页面上
//            if (StringUtils.endsWithIgnoreCase(redirectUrl, ".html")){
                //配置登录页面
                redirectStrategy.sendRedirect(request, response, securityProperties.getBrowser().getLoginPage());
//            }
        }

        return new SimpleResponse("访问的服务需要认证，请引导用户到登陆页面");
    }

}